package com.cxq.boot.controller;

import com.cxq.boot.dto.PaginationDTO;
import com.cxq.boot.model.User;
import com.cxq.boot.service.NotificationService;
import com.cxq.boot.service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;

@Controller
public class ProfileController {
    @Autowired
    private QuestionService questionService;
    @Autowired
    private NotificationService notificationService;

    @GetMapping("/profile/{action}")
    public String profile(HttpServletRequest request,
                          @PathVariable("action") String action,
                          Model model,
                          @RequestParam(value = "page", defaultValue = "1") Integer page,
                          @RequestParam(value = "size", defaultValue = "5") Integer size) {
        //从SessionInterceptor获取用户
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            return "redirect:/";
        }

        if ("questions".equals(action)) {
            model.addAttribute("section", "questions");
            model.addAttribute("sectionName", "我的提问");

            //问题分页
            PaginationDTO pagination = questionService.listByUserId(user.getId(), page, size);
            model.addAttribute("pagination", pagination);
        } else if ("replies".equals(action)) {
            model.addAttribute("section", "replies");
            model.addAttribute("sectionName", "最新回复");

            //最新回复数，将其SessionInterceptor校验并放入session
            /*Long unreadCount = notificationService.unreadCount(user.getId());
            model.addAttribute("unreadCount",unreadCount);*/

            //通知分页
            PaginationDTO pagination = notificationService.listByUserId(user.getId(), page, size);
            model.addAttribute("pagination", pagination);
        }

        return "profile";
    }
}
